package by.alex.dzeshko.facebooksuperclient;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;
import by.alex.dzeshko.facebooksuperclient.adapter.FeedCursorAdapter;
import by.alex.dzeshko.facebooksuperclient.api.ApiRequest;
import by.alex.dzeshko.facebooksuperclient.constants.FbConstants;
import by.alex.dzeshko.facebooksuperclient.database.DbNewsfeedHelper;
import by.alex.dzeshko.facebooksuperclient.http.HttpManager;
import by.alex.dzeshko.facebooksuperclient.http.RequestBuilder;
import by.alex.dzeshko.facebooksuperclient.providers.contract.FbContract;
import by.alex.dzeshko.facebooksuperclient.service.CommonService;
import by.alex.dzeshko.facebooksuperclient.service.FeedService;
import by.alex.dzeshko.facebooksuperclient.utils.InetChecker;
import by.alex.dzeshko.facebooksuperclient.utils.ViewHider;

public class ListNewsFragment extends ListFragment implements OnScrollListener {
	
	private static final String TAG = "tag";

	private static final String LOG_TAG = "ListNewsFragment";

	private ListView mListViewNews;
	
	private ImageButton mButtonRefresh, mButtonAdd;
	
	private View mViewLoading, mViewRefreshing;

	private String mNextPageUrl;
	
	private boolean mIsLoading;
	
	private BroadcastReceiver mBroadcastReciviver;
	
	private FeedCursorAdapter mNewsAdapter;

	private boolean mViewLoadingHidden, mViewRefreshingHidden;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mNewsAdapter = new FeedCursorAdapter(ContextHolder.getInstance().getContext(), null);
		android.support.v4.app.LoaderManager loader = getLoaderManager();
		loader.initLoader(0, null, new LoaderCallbacks<Cursor>() {

			@Override
			public Loader<Cursor> onCreateLoader(int paramInt, Bundle paramBundle) {
				String where = FbContract.NEWS;
				return new CursorLoader(getActivity(), FbContract.FeedColumns.CONTENT_URI, null, where, null, null);
			}

			@Override
			public void onLoadFinished(Loader<Cursor> paramLoader, Cursor paramD) {
				mNewsAdapter.swapCursor(paramD);
			}

			@Override
			public void onLoaderReset(Loader<Cursor> paramLoader) {
				mNewsAdapter.swapCursor(null);
			}
		});
		mBroadcastReciviver = new BroadcastReceiver() {
			
			@Override
			public void onReceive(Context context, Intent intent) {
				String action = intent.getAction();
				if (action.equals(FeedService.NEWS_ON_ERROR)) {
					hideViewRefreshing(true);
					hideViewLoading(true);
					mIsLoading = false;
					Toast.makeText(getActivity(), intent.getStringExtra(CommonService.EXTRA_KEY_MESSAGE),Toast.LENGTH_SHORT).show();
				} else if (action.equals(FeedService.NEWS_ON_SUCCESS)) {
					if(!mViewRefreshingHidden) hideViewRefreshing(true);
					mIsLoading = false;
					mNextPageUrl = intent.getStringExtra(FeedService.NEXT_PAGE);
					if(mNextPageUrl==null || mNextPageUrl.equals(FeedService.NO_PAGES)) hideViewLoading(true);
				}
			}
		};
		
		IntentFilter filter = new IntentFilter();
		filter.addAction(FeedService.NEWS_ON_ERROR);
		filter.addAction(FeedService.NEWS_ON_SUCCESS);
		ContextHolder.getInstance().getContext().registerReceiver(mBroadcastReciviver, filter);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		ViewGroup v = (ViewGroup) inflater.inflate(R.layout.fragment_list_news, null);
		setRetainInstance(true);
		mIsLoading = false;
		mNextPageUrl = FeedService.NO_PAGES;
		mListViewNews = (ListView) v.findViewById(android.R.id.list);
		mViewLoading = inflater.inflate(R.layout.view_listitem_loading, null);
		mViewRefreshing = inflater.inflate(R.layout.view_refreshig, null);
		mViewLoading.setTag(R.string.tag, TAG);
		mViewRefreshing.setTag(R.string.tag, TAG);
		mListViewNews.addFooterView(mViewLoading);
		mListViewNews.addHeaderView(mViewRefreshing);
		hideViewRefreshing(true);
		hideViewLoading(true);
		mListViewNews.setAdapter(mNewsAdapter);
		mListViewNews.setOnScrollListener(this);
		mButtonRefresh = (ImageButton) v.findViewById(R.id.btnRefresh);
		mButtonRefresh.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(!InetChecker.checkInetConnection(getActivity())){
					return;
				}
				mIsLoading=true;
				hideViewRefreshing(false);
				DbNewsfeedHelper dbHelper = new DbNewsfeedHelper(getActivity().getApplicationContext(), null);
				dbHelper.deleteItem(FbContract.FeedColumns.TABLE_TYPE, FbContract.NEWS);
				dbHelper.close();
				String url = ApiRequest.getNewsFeed();
				//TODO
				loadFeedPage(ApiRequest.addToken(url)+"&limit=5");

			}
		});
		mButtonAdd = (ImageButton) v.findViewById(R.id.btnNewPost);
		mButtonAdd.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(!InetChecker.checkInetConnection(getActivity())){
					return;
				}
				Intent post = new Intent(getActivity(), NewPostActivity.class);
				post.putExtra(FbConstants.ID, getActivity().getString(R.string.graph_api_me));
				startActivityForResult(post,0);
			}
		});
		return v;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		ContextHolder.getInstance().getContext().unregisterReceiver(mBroadcastReciviver);
	}

	@Override
	public void onResume() {
		super.onResume();
		mNewsAdapter.notifyDataSetChanged();
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
		if (visibleItemCount > 0 && firstVisibleItem + visibleItemCount + 2 >= totalItemCount && !mNextPageUrl.equals(FeedService.NO_PAGES)) {
			if(!mIsLoading){
				mIsLoading = true;
				if(mViewLoadingHidden) hideViewLoading(false);
				loadFeedPage(mNextPageUrl);
			}
		}
	}
	
	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		InetChecker.checkInetConnection(getActivity());
		Cursor cursor = (Cursor) l.getItemAtPosition(position);
		Intent intent = new Intent(this.getActivity(), FeedItemActivity.class);
		intent.putExtra(FbConstants.ITEM_ID, cursor.getString(cursor.getColumnIndex(FbContract.FeedColumns.ITEM_ID)));
		intent.putExtra(FbConstants.USER_ID, cursor.getString(cursor.getColumnIndex(FbContract.FeedColumns.FROM_ID)));
		intent.putExtra(FbConstants.FEED_TYPE, cursor.getString(cursor.getColumnIndex(FbContract.FeedColumns.TABLE_TYPE)));
		startActivity(intent);
		
	}

	@Override
	public void onScrollStateChanged(AbsListView arg0, int arg1) { }
	
	public void loadFeedPage(String url) {
		Intent intent = new Intent(getActivity(), FeedService.class);
		RequestBuilder requestBuilder = new RequestBuilder();
		requestBuilder.setType(RequestBuilder.Type.GET);
		requestBuilder.setUrl(url);
		requestBuilder.setDbMarker(FbContract.NEWS);
		intent.putExtra(FeedService.HTTP_REQUEST_BUILDER, requestBuilder);
		getActivity().startService(intent);
	}

	private void hideViewRefreshing(boolean hide){
		mViewRefreshingHidden=hide;
		ViewHider.hideListItem(mViewRefreshing, hide);
	}

	private void hideViewLoading(boolean hide){
		mViewLoadingHidden=hide;
		ViewHider.hideListItem(mViewLoading, hide);
	}

}
